package com.easylinkin.linkappapi.facerecognition.service;

import com.easylinkin.linkappapi.facerecognition.service.rest.BaiduManagementClientService;
import com.google.gson.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import retrofit2.Call;
import retrofit2.Response;

import java.io.IOException;

@Component
@ConditionalOnProperty(value = "ai.face.platform", havingValue = "baidu")
public class BaiduFaceAccessToken {

    private static final Logger log = LoggerFactory.getLogger(BaiduFaceAccessToken.class);

    @Autowired
    private BaiduManagementClientService baiduManagementClient;

    private static String ACCESS_TOKEN = "";

    @Value("${ai.face.baidu.ak}")
    private String apiKey;

    @Value(("${ai.face.baidu.sk}"))
    private String secretKey;

    public synchronized String accessToken() {
        if (ACCESS_TOKEN.isEmpty()) {
            Call<JsonObject> baiduAccessCall = baiduManagementClient.accessToken(apiKey, secretKey, "client_credentials");
            try {
                Response<JsonObject> accessResponse = baiduAccessCall.execute();
                if (accessResponse.isSuccessful()) {
                    ACCESS_TOKEN = accessResponse.body().get("access_token").getAsString();
                }
            } catch (IOException e) {
                log.error("access baidu access token error, ", e);
            }
        }

        return ACCESS_TOKEN;
    }

    /**
     * 固定每隔一天重置百度Token
     * */
    @Scheduled(fixedDelay = 24 * 60 * 60 * 1000)
    public synchronized void refreshAccessTokenEveryDay() {
        ACCESS_TOKEN = "";
    }
}
